package com.jd.org.service.impl;

import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.basic.util.MD5Utils;
import com.jd.basic.util.StrUtils;
import com.jd.org.domain.Employee;
import com.jd.org.mapper.EmployeeMapper;
import com.jd.org.service.EmployeeService;
import com.jd.user.domain.Logininfo;
import com.jd.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements EmployeeService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    @Transactional
    public void save(Employee employee) {
        // 处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);

        // 保存logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0); // 管理员
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);

        employee.setLogininfo_id(logininfo.getId());
        super.save(employee);
        if (employee.getRole_id()!=null) {
            // 保存中间表的信息
            employeeMapper.addEmployeeRole(employee);
        }
    }

    @Override
    @Transactional
    public void del(Long id) {
        Employee employee = employeeMapper.loadById(id);
        // 删除登录信息表数据
        logininfoMapper.del(employee.getLogininfo_id());
        // 通过employeeid删除中间表信息：t_employee_role
        employeeMapper.delEmployeeRoleById(id);
        // 删除employee表数据
        super.del(id);
    }

    @Override
    @Transactional
    public void update(Employee employee) {
        // 处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);

        super.update(employee);

        // 获取登录信息id
        Long logininfoId = employeeMapper.loadById(employee.getId()).getLogininfo_id();

        // 创建logininfoId
        Logininfo logininfo = logininfoMapper.loadById(logininfoId);
        // 将新的数据覆盖旧的数据
        BeanUtils.copyProperties(employee,logininfo);// 5个数据是新的 ：用户名，邮箱，电话，盐值，密码


        logininfoMapper.update(logininfo);

        // 删除中间表信息
        employeeMapper.delEmployeeRoleById(employee.getId());
        if (employee.getRole_id()!=null) {
            // 保存中间表的信息
            employeeMapper.addEmployeeRole(employee);
        }

    }


    @Override
    public List<Employee> findByShopId(Long shopId) {
        return employeeMapper.findByShopId(shopId);
    }
}
